//server.cpp
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>
using namespace cv;

int main(int, char **)
{
    zmq::context_t context(1); 
    zmq::socket_t publisher(context, ZMQ_PUB);
    //std::string addr = "tcp://*:5555";
    std::string addr = "ipc:///tmp/zmq";
    publisher.bind(addr);

    cv::Mat frame;
    cv::VideoCapture cap;
    // cap.open("rtsp://10.40.27.248/user=admin_password=tlJwpbo6_channel=1_stream=0.sdp?real_stream");
    bool isopend = cap.open(0);
    if (!isopend)
    {
        std::cout << "open video failed!" << std::endl;
    }

    while (cap.isOpened())
    {
        cap >> frame;
        //std::cout << frame.cols << " " << frame.rows << std::endl;
        
        int width = frame.cols;
        int height = frame.rows;
        int channel = frame.channels();
        uint32_t img_size = frame.total()*frame.elemSize();

        std::string zmq_data;
        zmq_data.resize(12 + img_size);
        memcpy((char*)zmq_data.data(), (char*)&width, 4);
        memcpy((char*)zmq_data.data() + 4, (char*)&height, 4);
        memcpy((char*)zmq_data.data() + 8, (char*)&channel, 4);
        memcpy((char*)zmq_data.data() + 12, (char*)frame.data, img_size);

        zmq::message_t msg(zmq_data.size());
        memcpy(msg.data(), zmq_data.data(), zmq_data.size());
        publisher.send(msg);
        // std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    cv::destroyAllWindows();
    cap.release();
    return 0;
}
